﻿using ManagementApi.TreeParty.SMS.LianXinTong;
using Modules.SMS;
using Modules.SMS.Entitys;
using Newtonsoft.Json;
using PmSoft;
using PmSoft.Utilities;
using System.Net;
using System.Reflection;

namespace ManagementApi.TreeParty.SMS;

/// <summary>
/// 联信通短信服务
/// </summary>
[UseDI(ServiceLifetime.Scoped, typeof(ISMSService))]
public class LXTSMSService : ISMSService
{
    private readonly IConfiguration configuration;
    private readonly SmsConfigModel smsConfig = new SmsConfigModel();
    private readonly SmsSendLogService smsSendLogService;
    private readonly ILogger logger;


    public LXTSMSService(
      IConfiguration configuration,
      SmsSendLogService smsSendLogService,
      ILogger<LXTSMSService> logger
      )
    {
        this.smsSendLogService = smsSendLogService;
        this.configuration = configuration;
        this.logger = logger;
        smsConfig.Url = configuration.GetValue<string>("ThreePartyOptions:LianXinTongSms:Url");
        smsConfig.AppID = configuration.GetValue<string>("ThreePartyOptions:LianXinTongSms:SpId");
        smsConfig.AppSecret = configuration.GetValue<string>("ThreePartyOptions:LianXinTongSms:AuthCode");
    }

    public bool Send(SmsSendLog sendLog)
    {
        string formUrl = smsConfig.Url + "/umpp/mt";
        SUBMIT_REQ req = new()
        {
            AuthCode = smsConfig.AppSecret ?? string.Empty,
            Content = sendLog.MsgContent,
            Mobiles = new string[] { sendLog.Phone },
            ReqId = Guid.NewGuid().ToString().Replace("-", ""),
            SpId = smsConfig.AppID ?? string.Empty
        };

        HttpResult result = HttpHelper.PostAsync(formUrl, JsonConvert.SerializeObject(req)).GetAwaiter().GetResult();

        if (result.Code == HttpStatusCode.OK)
        {
            var rsp = JsonConvert.DeserializeObject<SUBMIT_RSP>(result.Data.ToString() ?? string.Empty);
            if (rsp != null && rsp.rets != null)
            {
                var rspDetail = rsp.rets.FirstOrDefault(m => m.Mobile == sendLog.Phone);
                if (rspDetail != null)
                {
                    sendLog.Status = rspDetail.Rspcod == 0 ? 1 : 0;
                    sendLog.ResultMsg = $"Rspcod={rspDetail.Rspcod}";
                }
            }
        }
        else
            logger.LogError("联信通短信服务请求异常， 错误代码={0}，错误信息={1}", result.Code, result.ErrorMsg);

        smsSendLogService.Update(sendLog);

        return sendLog.Status == 1;
    }
 
}




